package com.imachen.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.imachen.ymcc.domain.User;
import com.imachen.ymcc.domain.UserIntegralLog;
import com.imachen.ymcc.domain.UserReferrer;
import com.imachen.ymcc.dto.IntegralDto;
import com.imachen.ymcc.enums.GlobalExceptionCode;
import com.imachen.ymcc.mapper.UserIntegralLogMapper;
import com.imachen.ymcc.service.IUserIntegralLogService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.imachen.ymcc.service.IUserReferrerService;
import com.imachen.ymcc.service.IUserService;
import com.imachen.ymcc.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author imachen
 * @since 2022-10-04
 */
@Service
public class UserIntegralLogServiceImpl extends ServiceImpl<UserIntegralLogMapper, UserIntegralLog> implements IUserIntegralLogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserReferrerService userReferrerService;

    /**
     * 积分赠送
     */
    @Override
    public void giveIntegral(IntegralDto integralDto) {
        Long userId = integralDto.getUserId(); // 用户id
        BigDecimal coursePrice = integralDto.getCoursePrice(); // 课程金额
        BigDecimal rechargePrice = integralDto.getRechargePrice(); // 充值金额
        BigDecimal payPrice = integralDto.getPayPrice(); // 支付金额

        AssertUtil.isNotNull(userId, GlobalExceptionCode.USER_IS_NULL_ERROR);
        // 购买课程送积分
        if (!coursePrice.equals(BigDecimal.ZERO) && !coursePrice.equals(null) && !coursePrice.equals("")){
            // 按照购买课程⾦额5%赠送积分
            bonusPoints(userId, coursePrice, 0.05);
            // 如果推荐的⼈购买课程，按照购买课程⾦额3%赠送积分
            // 根据userId查询推荐人id
            Wrapper<UserReferrer> wrapper = new EntityWrapper<>();
            wrapper.eq("user_id",userId);
            UserReferrer userReferrer = userReferrerService.selectOne(wrapper);
            if ( userReferrer != null){
                Long referrerId = userReferrer.getReferrerId(); // 推荐人id
                bonusPoints(referrerId, coursePrice, 0.03);
            }
        }
        // 充值送积分
        if (!rechargePrice.equals(BigDecimal.ZERO) && !rechargePrice.equals(null) && !rechargePrice.equals("")){
            // 充值按照充值⾦额5%赠送积分
            bonusPoints(userId, rechargePrice, 0.05);
        }

    }

    // 积分赠送方法
    private void bonusPoints(Long userId, BigDecimal price, double discount) {
        User user = userService.selectById(userId);
        int newIntValue = price.multiply(BigDecimal.valueOf(discount)).intValue();
        user.setIntegral(user.getIntegral() + newIntValue);
        userService.updateById(user);
        // 记录日志t_user_integral_log
        UserIntegralLog userIntegralLog = new UserIntegralLog();
        userIntegralLog.setCurrentTime(new Date());
        userIntegralLog.setUserId(userId);
        userIntegralLog.setIntegral("赠送积分：" + newIntValue);
        insert(userIntegralLog);
    }



    /**
     * 积分扣减 支付时
     */
    @Override
    public String reduceIntegral(IntegralDto integralDto) {
        Long userId = integralDto.getUserId();
        BigDecimal payPrice = integralDto.getPayPrice(); //支付金额
        // 查询当前用户的积分
        User user = userService.selectById(userId);
        AssertUtil.isNotNull(user,GlobalExceptionCode.USER_IS_NULL_ERROR);
        Integer integral = user.getIntegral(); // 当前用户积分
        // 支付金额所需要的积分 10 积分 = 1元
        int payIntegral = payPrice.multiply(BigDecimal.valueOf(10)).intValue();
        // 当用户积分大于支付金额时,扣掉相应积分
        int reduceIntegral = 0; // 扣除的积分
        String intro = "";
        if (integral > payIntegral){
            reduceIntegral = integral - payIntegral;
            user.setIntegral(reduceIntegral);
            intro = "已使用积分抵扣";
        }else { // 用户积分小于支付金额时
            reduceIntegral = integral;
            user.setIntegral(0);
            // 剩余的支付金额
            integralDto.setPayPrice(new BigDecimal((payIntegral - integral)/10));
            intro = "积分全部抵扣后还需支付金额："+ integralDto.getPayPrice() +" 元";
        }
        userService.updateById(user);
        System.out.println(intro);
        // 记录日志
        UserIntegralLog userIntegralLog = new UserIntegralLog();
        userIntegralLog.setCurrentTime(new Date());
        userIntegralLog.setUserId(userId);
        userIntegralLog.setIntegral("支付扣减积分：" + reduceIntegral);
        insert(userIntegralLog);

        return intro;

    }
}
